{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 层级索引（hierarchical indexing）（机器学习，深度学习不重要）",
   "id": "44e23dbd978edea3"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:34:16.703658Z",
     "start_time": "2025-01-08T07:34:16.261279Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "#MultiIndex是层级索引，索引类型的一种\n",
    "index1 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],\n",
    "                [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]], names=['cloth', 'size'])\n",
    "\n",
    "ser_obj = pd.Series(np.random.randn(12),index=index1)\n",
    "print(ser_obj)\n",
    "print(type(ser_obj)) #Series\n",
    "print(type(ser_obj.index)) #索引类型，MultiIndex\n",
    "print(ser_obj.index)\n",
    "print(ser_obj.index.levels) #层级索引的索引值\n",
    "ser_obj.index.codes  #没那么重要，代表索引的位置"
   ],
   "id": "75dc8763b304b8d3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth  size\n",
      "a      0      -0.310267\n",
      "       1      -1.013075\n",
      "       2      -1.089582\n",
      "b      0      -1.087634\n",
      "       1      -1.150795\n",
      "       2       1.092486\n",
      "c      0       0.044652\n",
      "       1      -0.505301\n",
      "       2      -0.046488\n",
      "d      0       0.587231\n",
      "       1       0.257575\n",
      "       2      -1.356149\n",
      "dtype: float64\n",
      "<class 'pandas.core.series.Series'>\n",
      "<class 'pandas.core.indexes.multi.MultiIndex'>\n",
      "MultiIndex([('a', 0),\n",
      "            ('a', 1),\n",
      "            ('a', 2),\n",
      "            ('b', 0),\n",
      "            ('b', 1),\n",
      "            ('b', 2),\n",
      "            ('c', 0),\n",
      "            ('c', 1),\n",
      "            ('c', 2),\n",
      "            ('d', 0),\n",
      "            ('d', 1),\n",
      "            ('d', 2)],\n",
      "           names=['cloth', 'size'])\n",
      "[['a', 'b', 'c', 'd'], [0, 1, 2]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "FrozenList([[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:35:02.748640Z",
     "start_time": "2025-01-08T07:35:02.742418Z"
    }
   },
   "cell_type": "code",
   "source": "ser_obj",
   "id": "7c7bc1d457b1ebf",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "cloth  size\n",
       "a      0      -0.310267\n",
       "       1      -1.013075\n",
       "       2      -1.089582\n",
       "b      0      -1.087634\n",
       "       1      -1.150795\n",
       "       2       1.092486\n",
       "c      0       0.044652\n",
       "       1      -0.505301\n",
       "       2      -0.046488\n",
       "d      0       0.587231\n",
       "       1       0.257575\n",
       "       2      -1.356149\n",
       "dtype: float64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:35:11.619257Z",
     "start_time": "2025-01-08T07:35:11.609271Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#层级索引如何取数据\n",
    "print('-'*50)\n",
    "print(ser_obj['c']) #取出c的所有数据，取出的是series\n",
    "print('-'*50)\n",
    "print(ser_obj.loc['a', 2])\n",
    "print('-'*50)\n",
    "print(ser_obj[:, 2]) #取出所有行的内层索引为2的数据"
   ],
   "id": "7c9bbb6751c82490",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------------------------------\n",
      "size\n",
      "0    0.044652\n",
      "1   -0.505301\n",
      "2   -0.046488\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "-1.0895822408911828\n",
      "--------------------------------------------------\n",
      "cloth\n",
      "a   -1.089582\n",
      "b    1.092486\n",
      "c   -0.046488\n",
      "d   -1.356149\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 交换层级",
   "id": "863bee877effd3d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:35:30.995306Z",
     "start_time": "2025-01-08T07:35:30.988603Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(ser_obj.swaplevel())\n",
    "print('-'*50)\n",
    "print(ser_obj)\n",
    "print('-'*50)\n",
    "ser_obj=ser_obj.swaplevel()\n",
    "print(ser_obj)"
   ],
   "id": "6a2e4ad1bba4e2fb",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a       -0.310267\n",
      "1     a       -1.013075\n",
      "2     a       -1.089582\n",
      "0     b       -1.087634\n",
      "1     b       -1.150795\n",
      "2     b        1.092486\n",
      "0     c        0.044652\n",
      "1     c       -0.505301\n",
      "2     c       -0.046488\n",
      "0     d        0.587231\n",
      "1     d        0.257575\n",
      "2     d       -1.356149\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "cloth  size\n",
      "a      0      -0.310267\n",
      "       1      -1.013075\n",
      "       2      -1.089582\n",
      "b      0      -1.087634\n",
      "       1      -1.150795\n",
      "       2       1.092486\n",
      "c      0       0.044652\n",
      "       1      -0.505301\n",
      "       2      -0.046488\n",
      "d      0       0.587231\n",
      "       1       0.257575\n",
      "       2      -1.356149\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "size  cloth\n",
      "0     a       -0.310267\n",
      "1     a       -1.013075\n",
      "2     a       -1.089582\n",
      "0     b       -1.087634\n",
      "1     b       -1.150795\n",
      "2     b        1.092486\n",
      "0     c        0.044652\n",
      "1     c       -0.505301\n",
      "2     c       -0.046488\n",
      "0     d        0.587231\n",
      "1     d        0.257575\n",
      "2     d       -1.356149\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:35:37.678514Z",
     "start_time": "2025-01-08T07:35:37.671470Z"
    }
   },
   "cell_type": "code",
   "source": "print(ser_obj.sort_index(level=0))  #层级索引按那个索引级别排序,level=0表示按最外层索引排序",
   "id": "984ac63f0d51ab07",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a       -0.310267\n",
      "      b       -1.087634\n",
      "      c        0.044652\n",
      "      d        0.587231\n",
      "1     a       -1.013075\n",
      "      b       -1.150795\n",
      "      c       -0.505301\n",
      "      d        0.257575\n",
      "2     a       -1.089582\n",
      "      b        1.092486\n",
      "      c       -0.046488\n",
      "      d       -1.356149\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:35:45.572582Z",
     "start_time": "2025-01-08T07:35:45.566178Z"
    }
   },
   "cell_type": "code",
   "source": "ser_obj",
   "id": "f4ba21e1ba8d887e",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "size  cloth\n",
       "0     a       -0.310267\n",
       "1     a       -1.013075\n",
       "2     a       -1.089582\n",
       "0     b       -1.087634\n",
       "1     b       -1.150795\n",
       "2     b        1.092486\n",
       "0     c        0.044652\n",
       "1     c       -0.505301\n",
       "2     c       -0.046488\n",
       "0     d        0.587231\n",
       "1     d        0.257575\n",
       "2     d       -1.356149\n",
       "dtype: float64"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:36:06.744709Z",
     "start_time": "2025-01-08T07:36:06.735306Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#把最大索引变为列索引\n",
    "df_obj=ser_obj.unstack()  #unstack的level参数是索引层级\n",
    "print(df_obj)"
   ],
   "id": "e508e2fa090c877e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0     -0.310267 -1.087634  0.044652  0.587231\n",
      "1     -1.013075 -1.150795 -0.505301  0.257575\n",
      "2     -1.089582  1.092486 -0.046488 -1.356149\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:36:20.879473Z",
     "start_time": "2025-01-08T07:36:20.872577Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(df_obj)\n",
    "#对df进行stack，就会把行，列索引进行堆叠，变为series\n",
    "#把列索引放入内层,只能放到内层\n",
    "print(df_obj.stack())  #stack变为series和unstack保持一致的\n",
    "# df_obj=df_obj.transpose()"
   ],
   "id": "f284251b17c77199",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0     -0.310267 -1.087634  0.044652  0.587231\n",
      "1     -1.013075 -1.150795 -0.505301  0.257575\n",
      "2     -1.089582  1.092486 -0.046488 -1.356149\n",
      "size  cloth\n",
      "0     a       -0.310267\n",
      "      b       -1.087634\n",
      "      c        0.044652\n",
      "      d        0.587231\n",
      "1     a       -1.013075\n",
      "      b       -1.150795\n",
      "      c       -0.505301\n",
      "      d        0.257575\n",
      "2     a       -1.089582\n",
      "      b        1.092486\n",
      "      c       -0.046488\n",
      "      d       -1.356149\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 8
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
